import Vue from 'vue'
import App from './App'
import store from '../../store'
import commonUtil from '../../util/commonUtil'
import eventBus from '../../plugins/eventBus'
import MyStorage from '../../plugins/MyStorage'

const udpUtil = require('../../util/udpUtil')

const userUtil = require('../../util/userUtil')
const msgUtil = require('../../util/msgUtil')

if (!process.env.IS_WEB) Vue.use(require('vue-electron'))
Vue.config.productionTip = false

Vue.use(eventBus)
Vue.use(MyStorage)

window.addEventListener('storage', async (ev) => {
  if (ev.key !== 'communication') return
  let arg = myStorage.getItem('communication', {})
  switch (arg.action) {
    case 'sendMsg':
      udpUtil.udpSend(arg.data.sendData, arg.data.sendIp)
      break
  }
})

let audio = new Audio()
audio.src = require('../../assets/notice.wav')
// audio.controls = 'controls'
audio.style.display = 'none'
document.body.appendChild(audio)

udpUtil.onMessage(async (msg) => {
  let ip = msg.ip
  let data = JSON.parse(msg.data)
  switch (data.action) {
    case 'listening':

      let messageList = await msgUtil.getMsgs()
      let userList = await userUtil.getUsers()

      store.dispatch('setUserList', userList)
      store.dispatch('setMessageList', messageList)

      let networkInfo = commonUtil.getNetworkInfo()

      let mineInfo = commonUtil.getMineInfo()
      udpUtil.udpSend(JSON.stringify({action: 'online-notice', data: mineInfo}), networkInfo.broadcastAddress)
      break
    case 'error':
      Vue.prototype.$electron.remote.dialog.showMessageBox(Vue.prototype.$electron.remote.getCurrentWindow(), {
        type: 'error',
        title: '程序出错了',
        message: data.data.message,
        detail: data.data.stack
      }, (action) => {
        if (action === 0) {
          Vue.prototype.$electron.remote.getCurrentWindow().close()
        }
      })
      break
    case 'online-notice':
      console.log(`收到${ip}上线通知`, data.data)
      userUtil.addUser({
        ...data.data,
        userip: ip,
        zt: 'online'
      })
      if (ip !== commonUtil.getNetworkInfo().address) {
        let mineInfo = commonUtil.getMineInfo()
        udpUtil.udpSend(JSON.stringify({action: 'inline-notice', data: mineInfo}), ip)
      }
      break
    case 'inline-notice':
      console.log(`收到${ip}在线回应`, data.data)
      userUtil.addUser({
        ...data.data,
        userip: ip,
        zt: 'online'
      })
      break
    case 'offline-notice':
      console.log(`收到${ip}下线通知`, data.data)
      // store.dispatch('setUser', {zt: 'offline', userip: ip})
      break
    case 'update-info':
      console.log(`${ip}修改资料`, data.data)
      userUtil.addUser({
        ...data.data,
        zt: 'online',
        userip: ip
      })
      break
    case 'msg':
      console.log('普通消息', data.data)

      let userInfo = await userUtil.getUser(ip)

      showNotification(`消息内容【${data.data.msg}】`, `收到【${userInfo.xm}】发来的消息`)
      audio.play()
      let msg = {
        ...data.data,
        type: 'receive',
        createtime: Date.now(),
        relationuserip: ip
      }
      await msgUtil.addMsg(msg)
      store.dispatch('addMessageList', msg)

      // 判断该消息是否需要加入未读
      if (store.state.currentIp !== ip) {
        Vue.prototype.$electron.ipcRenderer.send('openUnread', true)
        store.dispatch('setUnreadCount', {action: 'add', ip: ip})
      } else {
        let win = Vue.prototype.$electron.remote.BrowserWindow.getFocusedWindow()
        if (!win || !/chatbox/.test(win.getURL())) {
          Vue.prototype.$electron.ipcRenderer.send('openUnread', true)
          store.dispatch('setUnreadCount', {action: 'add', ip: ip})
        }
      }
      break
  }
})

udpUtil.start()

function showNotification (message, title, options) {
  let n = new Notification(title,
    {
      icon: '',
      body: message
    })
  n.onshow = function () {
    console.log('显示通知')
  }
  n.onclick = function () {
    // alert('打开相关视图')
    // window.open('/Home/about')
    // n.close()
  }
  n.onclose = function () {
    console.log('通知关闭')
  }
  n.onerror = function () {
    console.log('产生错误')
  }
}

/* eslint-disable no-new */
new Vue({
  components: {App},
  // router,
  store,
  template: '<App/>'
}).$mount('#app')
